"""Email service for sending emails (Synchronous).

统一使用同步实现，遵循 DEVELOPMENT_GUIDE.md 同步优先原则。
"""

from __future__ import annotations

from typing import Any, Optional
import logging
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

from ..core.config import settings

logger = logging.getLogger(__name__)


class EmailService:
    """Service for sending emails (Synchronous)."""

    @staticmethod
    def send_email(
        email_to: str,
        subject: str,
        body: str,
        template_name: Optional[str] = None,
        template_data: Optional[dict[str, Any]] = None,
    ) -> bool:
        """
        Send an email to the specified recipient (Synchronous).

        使用SMTP协议发送邮件，支持多种邮件服务：
        - 阿里云邮件推送
        - SendGrid
        - 自建SMTP服务器

        Args:
            email_to: Recipient email address
            subject: Email subject
            body: Email body content
            template_name: Optional template name to use
            template_data: Optional data for template rendering

        Returns:
            bool: True if email was sent successfully, False otherwise
        """
        # 检查SMTP配置是否完整
        if not settings.SMTP_HOST or not settings.SMTP_USERNAME:
            logger.warning(
                f"SMTP配置不完整，邮件发送降级为日志记录 "
                f"(SMTP_HOST={settings.SMTP_HOST}, SMTP_USERNAME={settings.SMTP_USERNAME})"
            )
            logger.info(f"[模拟发送] 收件人: {email_to}, 主题: {subject}")
            logger.info(f"[模拟发送] 内容: {body[:100]}...")
            return True

        try:
            # 构建邮件
            msg = MIMEMultipart("alternative")
            msg["From"] = settings.SMTP_USERNAME
            msg["To"] = email_to
            msg["Subject"] = subject

            # 邮件正文（支持HTML）
            text_part = MIMEText(body, "plain", "utf-8")
            msg.attach(text_part)

            # 可选：添加HTML版本
            # html_part = MIMEText(body, 'html', 'utf-8')
            # msg.attach(html_part)

            # 连接SMTP服务器并发送
            logger.info(f"连接SMTP服务器: {settings.SMTP_HOST}:{settings.SMTP_PORT}")

            with smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT, timeout=10) as server:
                # 启用TLS加密（推荐）
                if settings.SMTP_PORT == 587:
                    server.starttls()

                # 登录SMTP服务器
                if settings.SMTP_PASSWORD:
                    server.login(settings.SMTP_USERNAME, settings.SMTP_PASSWORD)

                # 发送邮件
                server.sendmail(settings.SMTP_USERNAME, [email_to], msg.as_string())

            logger.info(f"邮件发送成功: {email_to} - {subject}")
            return True

        except smtplib.SMTPAuthenticationError as e:
            logger.error(f"SMTP认证失败: {str(e)} - 请检查SMTP_USERNAME和SMTP_PASSWORD")
            return False
        except smtplib.SMTPConnectError as e:
            logger.error(f"SMTP连接失败: {str(e)} - 请检查SMTP_HOST和SMTP_PORT")
            return False
        except smtplib.SMTPException as e:
            logger.error(f"SMTP发送失败: {str(e)}")
            return False
        except Exception as e:
            logger.error(f"邮件发送异常: {type(e).__name__} - {str(e)}")
            return False

    @staticmethod
    def send_password_reset_email(
        email_to: str, token: str, user_name: Optional[str] = None
    ) -> bool:
        """
        Send a password reset email with a token (Synchronous).

        Args:
            email_to: Recipient email address
            token: Password reset token
            user_name: Optional user display name

        Returns:
            bool: True if email was sent successfully, False otherwise
        """
        subject = "Password Reset Request"

        # 构建邮件正文
        greeting = f"Hello {user_name}," if user_name else "Hello,"
        body = f"""{greeting}

You have requested to reset your password for your account.

Please use the following token to reset your password:

Token: {token}

This token will expire in 24 hours.

If you did not request this password reset, please ignore this email.

Best regards,
The Team
"""
        return EmailService.send_email(email_to, subject, body)

    @staticmethod
    def send_verification_email(email_to: str, token: str) -> bool:
        """
        Send an email verification email with a token (Synchronous).

        Args:
            email_to: Recipient email address
            token: Verification token

        Returns:
            bool: True if email was sent successfully, False otherwise
        """
        subject = "Email Verification"
        body = f"""Hello,

Please verify your email address by using the following token:

Token: {token}

This token will expire in 24 hours.

Best regards,
The Team
"""
        return EmailService.send_email(email_to, subject, body)

    @staticmethod
    def send_bulk_email(
        emails_to: list[str],
        subject: str,
        body: str,
        template_name: Optional[str] = None,
        template_data: Optional[dict[str, Any]] = None,
    ) -> bool:
        """
        Send an email to multiple recipients (Synchronous).

        Args:
            emails_to: List of recipient email addresses
            subject: Email subject
            body: Email body content
            template_name: Optional template name to use
            template_data: Optional data for template rendering

        Returns:
            bool: True if all emails were sent successfully, False otherwise
        """
        success = True
        for email in emails_to:
            result = EmailService.send_email(email, subject, body, template_name, template_data)
            if not result:
                success = False
        return success
